"""
修复和重新生成损坏的语音文件
"""

import os
import wave
from pathlib import Path

def is_valid_wav(file_path):
    """检查 WAV 文件是否有效"""
    try:
        # 检查文件大小
        size = os.path.getsize(file_path)
        if size < 1000:  # 小于 1KB 可能有问题
            return False, f"文件太小 ({size} bytes)"
        
        # 检查文件头
        with open(file_path, 'rb') as f:
            header = f.read(12)
            if len(header) < 12:
                return False, "文件头不完整"
            
            if header[0:4] != b'RIFF':
                # 可能是错误消息
                with open(file_path, 'rb') as f:
                    content = f.read(200)
                    try:
                        text = content.decode('utf-8', errors='ignore')
                        if 'error' in text.lower():
                            return False, f"包含错误消息: {text[:50]}"
                    except:
                        pass
                return False, "不是 RIFF 格式"
            
            if header[8:12] != b'WAVE':
                return False, "不是 WAVE 格式"
        
        # 尝试用 wave 模块打开
        with wave.open(str(file_path), 'rb') as wav:
            frames = wav.getnframes()
            if frames == 0:
                return False, "没有音频数据"
        
        return True, "有效"
        
    except Exception as e:
        return False, str(e)

def scan_and_fix(speech_dir):
    """扫描并修复语音文件夹"""
    speech_path = Path(speech_dir)
    
    if not speech_path.exists():
        print(f"❌ 目录不存在: {speech_dir}")
        return []
    
    print("="*70)
    print("🔍 扫描语音文件")
    print("="*70)
    print()
    
    wav_files = sorted(speech_path.glob("p*.wav"))
    
    if not wav_files:
        print("❌ 没有找到 WAV 文件")
        return []
    
    invalid_files = []
    
    for wav_file in wav_files:
        size = os.path.getsize(wav_file)
        is_valid, reason = is_valid_wav(wav_file)
        
        if is_valid:
            print(f"✅ {wav_file.name:12} - {size:>10,} bytes - {reason}")
        else:
            print(f"❌ {wav_file.name:12} - {size:>10,} bytes - {reason}")
            invalid_files.append(wav_file)
    
    print()
    print("="*70)
    print(f"📊 统计")
    print("="*70)
    print(f"  总文件: {len(wav_files)}")
    print(f"  有效: {len(wav_files) - len(invalid_files)}")
    print(f"  损坏: {len(invalid_files)}")
    print()
    
    return invalid_files

def delete_invalid_files(invalid_files):
    """删除无效文件"""
    if not invalid_files:
        print("✅ 没有需要删除的文件")
        return
    
    print("="*70)
    print("🗑️  准备删除以下文件:")
    print("="*70)
    for f in invalid_files:
        print(f"  - {f}")
    print()
    
    response = input("确认删除? (y/N): ").strip().lower()
    
    if response == 'y':
        for f in invalid_files:
            try:
                f.unlink()
                print(f"  ✅ 已删除: {f.name}")
            except Exception as e:
                print(f"  ❌ 删除失败: {f.name} - {e}")
        print()
        print("✅ 删除完成!")
        print()
        print("下一步:")
        print("  运行: python run_interactive.py --config mm_story_agent.yaml")
        print("  程序会自动跳过已存在的文件,只重新生成被删除的文件")
    else:
        print("❌ 取消删除")

def main():
    """主函数"""
    import sys
    
    speech_dir = "generated_stories/example/speech"
    
    if len(sys.argv) > 1:
        speech_dir = sys.argv[1]
    
    print("="*70)
    print("🔧 语音文件修复工具")
    print("="*70)
    print()
    
    # 扫描
    invalid_files = scan_and_fix(speech_dir)
    
    # 删除
    if invalid_files:
        delete_invalid_files(invalid_files)
    else:
        print("="*70)
        print("✅ 所有文件都有效!")
        print("="*70)
        print()
        print("如果视频合成仍然失败,可能的原因:")
        print()
        print("1. ffmpeg 版本问题")
        print("   解决: 重新安装 ffmpeg")
        print()
        print("2. MoviePy 版本问题")
        print("   解决: pip install moviepy==1.0.3")
        print()
        print("3. 文件路径问题")
        print("   解决: 使用绝对路径")

if __name__ == "__main__":
    main()
